package com.tmian.aiagent.Advisor;

import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;

//重复读文本日志
public class ReReadingAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {
    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        AdvisedRequest request = this.before(advisedRequest);
        AdvisedResponse advisedResponse = chain.nextAroundCall(request);
        return advisedResponse;
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        AdvisedRequest request = this.before(advisedRequest);
        Flux<AdvisedResponse> advisedResponseFlux = chain.nextAroundStream(request);
        return advisedResponseFlux;
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }

    public AdvisedRequest before(AdvisedRequest advisedRequest) {
        HashMap<String, Object> userParam = new HashMap<>(advisedRequest.userParams());

        userParam.put("re2_input_query", advisedRequest.userText());

        AdvisedRequest.from(advisedRequest)
                .userText("""
                        {re2_input_query}
                        Read the question again: {re2_input_query}
                        """)
                .userParams(userParam)
                .build();

        return advisedRequest;
    }
}
